package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiguliuxing.dts.db.dao.DtsSearchHistoryMapper;
import com.qiguliuxing.dts.db.domain.DtsSearchHistory;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsSearchHistoryService {
	@Resource
	private DtsSearchHistoryMapper searchHistoryMapper;

	public void save(DtsSearchHistory searchHistory) {
		searchHistory.setAddTime(LocalDateTime.now());
		searchHistory.setUpdateTime(LocalDateTime.now());
		searchHistoryMapper.insert(searchHistory);
	}

	public List<DtsSearchHistory> queryByUid(int uid) {
		QueryWrapper<DtsSearchHistory> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsSearchHistory::getUserId, uid);
		queryWrapper.lambda().eq(DtsSearchHistory::getDeleted, false);
		// 	example.setDistinct(true); TODO 待修改
		return searchHistoryMapper.selectList(queryWrapper);
	}

	public void deleteByUid(int uid) {
		QueryWrapper<DtsSearchHistory> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsSearchHistory::getUserId, uid);
		searchHistoryMapper.delete(queryWrapper);
	}

	public List<DtsSearchHistory> querySelective(String userId, String keyword, Integer page, Integer size, String sort,
			String order) {
		QueryWrapper<DtsSearchHistory> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(userId)) {
			queryWrapper.lambda().eq(DtsSearchHistory::getUserId, userId);
		}
		if (StrUtil.isNotEmpty(keyword)) {
			queryWrapper.lambda().like(DtsSearchHistory::getKeyword, keyword);
		}
		queryWrapper.lambda().eq(DtsSearchHistory::getDeleted, false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}
		IPage<DtsSearchHistory> iPage = new Page<>(page, size);
		return searchHistoryMapper.selectPage(iPage, queryWrapper).getRecords();
	}
}
